package org.votes.dao.impl;

import java.util.List;

import javax.persistence.Entity;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.votes.bean.Details;
import org.votes.dao.DetailsDao;

@Entity
@Repository("detailsDao")
public class DetailsDaoImpl implements DetailsDao {
	
	@Autowired
	private SessionFactory sessionFactory;
	

	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	
	
	@Override
	public boolean add(Details detail) {
		getSession().save(detail);
		return true;
	}

	@Override
	public Details update(Details detail) {
		String sql = "update votes.details set details.count1 = " +detail.getCount1()+ " , details.count2 = " +detail.getCount2()+ "" +
				" , details.count3 = " +detail.getCount3() + " , details.count4 = "+detail.getCount4()+" where details.id = " + detail.getId();
		System.out.println(sql);
		getSession().createSQLQuery(sql).executeUpdate();
//		Query query = getSession().createQuery("from Details where id = " + detail.getId());
//		Details newDetail =(Details) query.list().get(0); 
		return detail;
	}

	@Override
	public boolean delete(Details detail) {
		getSession().delete(detail);
		return true;
	}

	@Override
	public List<Details> findAll() {
		Query query = getSession().createQuery("from Details");
		List<Details> list = query.list();
		return list;
	}


	@Override
	public Details findById(int id) {
		Query query = getSession().createQuery("from Details where id = " + id);
		List<Details> list = query.list();
		if(list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

}
